package com.fooddiary.service.impl;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fooddiary.dao.IModelDao;
import com.fooddiary.dao.IUserDao;
import com.fooddiary.model.Model;
import com.fooddiary.model.User;
import com.fooddiary.service.IModelService;
import com.fooddiary.util.AppException;

/**
 * Implements business logic operations for model <br>
 * @author Created by andrey.kuznetsov <br>
 * @author Last modified by $Author$ <br>
 * @author Last modified on $Date$ at revision $Revision$ <br>
 */
@Service
public class ModelService extends AbstractService implements IModelService{
	
	@Autowired
	IModelDao modelDao;

	@Autowired
	IUserDao userDao;
	
	@Override
	@Transactional(readOnly=true)
	public Model getModel() throws AppException {
		SecurityContext securityContext = SecurityContextHolder.getContext();
		Model model = null; 
		if(securityContext == null || securityContext.getAuthentication() == null || securityContext.getAuthentication().getPrincipal() == null){
			throw new AppException( messageSource.getMessage( "message.error.common", null, null ));
		}
		String login = null;
		Object principal = securityContext.getAuthentication().getPrincipal();
		if(principal instanceof UserDetails){
			login =((org.springframework.security.core.userdetails.User) principal).getUsername();
		}else {
			login = principal.toString();
		}
		
		if(StringUtils.isEmpty( login )){
			throw new AppException( 
					messageSource.getMessage( "message.error.common", null, null ) );	
		}
		User userDB = userDao.getUserByLogin( login );
		if(userDB != null){
			model = userDB.getModel();
		}else{
			throw new AppException( 
					messageSource.getMessage( "message.error.common", null , null ) );
		}
		return model;
	}
}
